/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccastestore.servlet;

import it.unitn.science.matr155863_148346_145963.bccastestore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.User;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.Crypto;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author berto
 */
public class LoginSRV extends HttpServlet {

    private DBManager db;
    private static Logger log = Logger.getLogger(LoginSRV.class);
    
    @Override
    public void init() throws UnavailableException{
            db=(DBManager)super.getServletContext().getAttribute("db_manager");
    }
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String address=request.getContextPath()+"/contents/public/home.jsp?login=true";
        //PrintWriter out=response.getWriter();
        try {
            /*
             * Faccio una query sul database per vedere se l'utente esiste e
             * se la password coincide (email e password).
             * Se tutto e' andato a buon fine, istanzio le variabili di sessione
             * neccessarie (Nome utente e id nel database dell'utente) 
             * e lo rimando alla index o dove voglio io.
             */
             String psw=request.getParameter("password");
            if(psw!=null){
                String crypto=Crypto.crypto(psw);
                User user=db.authenticate(request.getParameter("username"),crypto);
                if(user!=null){
                    request.getSession().setAttribute("user", user);
                //out.println("<h2>Hello"+user.getFirst_name()+" "+user.getLast_name()+"</h2>");
                }
            }
        }catch(Exception ex){
            log.error(ex);
            address=request.getContextPath()+"/contents/public/errorPage.jsp";
            //out.println("<h2>Ops</h2><p>there was an error.<br/>Please retry.</p>");
        } finally {           
            //RequestDispatcher dispatcher =request.getRequestDispatcher(address);
            //dispatcher.include(request, response);
            //dispatcher.forward(request, response);
            
            response.sendRedirect(response.encodeRedirectURL(address));
            /*
             * Cambia se uso redirect o forward, perche' uno ritorna tutto al
             * client e poi lo ridirige e l'altro lo ridirige subito
             */
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
